import { getUserInfo, login } from "@/api/system/user";
import { storage } from "@/utils/lib/Storage";
import { defineStore } from "pinia";
import { ACCESS_TOKEN, CURRENT_ADMIN } from "../mutation-types";

interface IState {
  token: string
  info: Record<string,any>
}

export const useUserStore = defineStore({
  id: 'app-user',
  state: (): IState => ({
    token: storage.get(ACCESS_TOKEN, ''),
    info: storage.get(CURRENT_ADMIN, {})
  }),
  actions: {
    setToken(token:string) {
      this.token = token
    },
    setUserInfo(info: Record<string, any>) {
        this.info = info
    },
    // 登录
    async userLogin(data) {
      try {
        const res = await login(data)
        if (res.data.code === 200) {
          const ex = 7 * 24 * 60 * 60
          storage.set(ACCESS_TOKEN, res.data.data.token, ex)
          this.setToken(res.data.data.token)
          return Promise.resolve(res)
        }
      } catch (error) {
        return Promise.reject(error)
      }
    },
    // 获取用户信息
    async getInfo(data) {
      try {
        const res = await getUserInfo(data)
        if (res.data.code === 200) {
          const ex = 7 * 24 * 60 * 60
          storage.set(CURRENT_ADMIN, res.data.data, ex)
          this.setUserInfo(res.data.data)
        }
        return Promise.resolve(res)
      } catch (error) {
        return Promise.reject(error)
      }
    }
  }
})